package kr.couponplay.android.activity.message;

import java.util.List;

import kr.couponplay.android.activity.R;
import kr.couponplay.android.domain.message.MessageList;
import kr.couponplay.android.support.DisplayUtils;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class MessageListViewAdapter extends ArrayAdapter<MessageList.Item> {
	private Context mContext;
	private int mResource;
	private List<MessageList.Item> items;
	private LayoutInflater mInflater;

	public MessageListViewAdapter(Context context, int layoutResource, List<MessageList.Item> items) {
		super(context, layoutResource, items);
		this.mContext = context;
		this.mResource = layoutResource;
		this.items = items;
		this.mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		MessageList.Item item = items.get(position);
		
		if (convertView == null) {
			convertView = mInflater.inflate(mResource, parent, false);
		}

		if (item != null) {
			TextView providerCode = (TextView) convertView.findViewById(R.id.message_providerCode);
			TextView receivedDate = (TextView) convertView.findViewById(R.id.message_receivedDate);
			TextView message = (TextView) convertView.findViewById(R.id.message_text);
			
			providerCode.setText(item.getProvider().getName());
			receivedDate.setText(DisplayUtils.dateFormat(item.getReceivedDate(), "yyyy-MM-dd HH:mm"));
			message.setText((item.getMessage().length() > 200)? item.getMessage().substring(0, 200) + ".." : item.getMessage());
			
			MessageOnClickListener messageOnClickListener = new MessageOnClickListener(mContext, this, position);
			message.setOnClickListener(messageOnClickListener);
		}
		return convertView;
	}
	
	public MessageList.Item getItem(int position) {
		return items.get(position);
	}
	
	public int getItemSize() {
		return items.size();
	}
}
